<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/15
 * Time: 10:09
 */

namespace frontend\widgets;


use common\models\c2\entity\UserGrade;
use common\models\c2\statics\UserGradeState;
use Yii;
use yii\base\Widget;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

class UserGradeChart extends Widget
{
    public $items;
    public $user;
    public $amoeba_id;
    public $data = "{}";

    public function init()
    {

        parent::init(); // TODO: Change the autogenerated stub
        if (!is_null($this->amoeba_id)) {
            //'amoeba_id' => $this->amoeba_id,
            $this->items = [];
            $this->items = UserGrade::find()
                ->where(['state' => UserGradeState::STATE_INIT])
                ->all();


            $this->data = [
                'id' => $this->user->id,
                'name' => $this->user->username,
                // 'parent_id' => $root->parent_station_id,
                'children' => $this->getUserGradeChildren($this->user->id),
            ];
            Yii::info($this->user->id);
//            Yii::info($this->data);
        }
    }

    public function isHasChildren($parent_id)
    {
        foreach ($this->items as $item) {
            if ($item->invite_user_id == $parent_id) {
                return true;
            }
        }
        return false;
    }

    public function getUserGradeChildren($parent_id)
    {
//        print_r($this->items);
        $rec = [];
        foreach ($this->items as $item) {
            if ($item->invite_user_id == $parent_id) {
                $children = [];
                if ($this->isHasChildren($item->join_user_id)) {
                    $children = $this->getUserGradeChildren($item->join_user_id);
                }
                $rec[] = [
                    'id' => $item->id,
                    'name' => $item->joinUser->username,
                    'children' => $children
                ];
            }
        }

        return $rec;
    }

    public function run()
    {
//        Yii::info($this->data);
        return $this->render('userGradeChart', [
            'data' => $this->data,
            'user' => $this->user,
        ]);
    }
}